﻿
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Yuebon.WebApi.Common
{
    /// <summary> 
    /// 隐藏接口，不生成到swagger文档展示 
    /// </summary> 
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public partial class HiddenApiAttribute : Attribute { }
    /// <summary>
    /// 隐藏接口，不生成到swagger文档展示 
    /// </summary>
    public class HiddenApiFilter : IDocumentFilter
    {
        /// <summary>
        /// 实现Apply方法
        /// </summary>
        /// <param name="swaggerDoc"></param>
        /// <param name="documentFilterContext"></param>
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext documentFilterContext)
        {
            foreach (ApiDescription apiDescription in documentFilterContext.ApiDescriptionsGroups.Items.SelectMany(e => e.Items))
            {
                if (apiDescription.ControllerAttributes().OfType<HiddenApiAttribute>().Count() == 0
               && apiDescription.ActionAttributes().OfType<HiddenApiAttribute>().Count() == 0) continue;

                var key = "/" + apiDescription.RelativePath.TrimEnd('/');
                if (!key.Contains("?") && swaggerDoc.Paths.ContainsKey(key))
                swaggerDoc.Paths.Remove(key);
            }
        }
    }
}
